package wheel.conversion.impl;

import wheel.conversion.Converter;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;

import java.util.Date;
import java.util.Map;

public class DateConverter extends Converter {
    public Class getTargetClass() {
        return Date.class;
    }
    
    public Object convert(String value, Map<String, String> params) {
        String format = "dd/MM/yyyy";
        if (params != null && 
                params.containsKey("$format")) {
            format = params.get("$format");
        }
        
        return stringToDate(value, format);
    }
    
    private Date stringToDate(String dateString, String format) {
        if (dateString == null) return null;
        
        Date date = null;
		DateFormat formatter = new SimpleDateFormat(format);
		try {
			date = (Date) formatter.parse(dateString);
		} catch(ParseException e) {
			e.printStackTrace();
		}
		return date;
    }
}
